package com.atguigu.interceptor;


import com.alibaba.fastjson.JSON;
import com.atguigu.constant.AtguiguConstant;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.Result;
import com.atguigu.result.ResultCodeEnum;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否已登录
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute(AtguiguConstant.sessionConstant.USER_KEY);
        if (userInfo == null) {
            //2.未登录，跳转到登录页面(异步请求中，不能用重定向进行跳转，没有效果，让前端自己跳)
            //2.1构建一个响应对象
            Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
            //2.2将result对象转成json字符串响应给前端
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        //已登录
        return true;
    }
}
